# monitor/models.py
from django.db import models
from timescale.db.models.models import TimescaleModel
from timescale.db.models.fields import TimescaleDateTimeField
from django.db.models import FloatField, IntegerField, BigIntegerField, JSONField


# Create your models here.
class ServerMetrics(TimescaleModel):
    time: TimescaleDateTimeField = TimescaleDateTimeField(
        primary_key=True,
        verbose_name="时间戳",
        interval="1 day",
    )  # type: ignore
    # CPU 指标
    cpu_percent: FloatField = FloatField(
        verbose_name="CPU使用率(%)",
    )
    cpu_user: FloatField = FloatField(
        verbose_name="用户CPU使用率(%)",
    )
    cpu_system: FloatField = FloatField(
        verbose_name="系统CPU使用率(%)",
    )
    cpu_iowait: FloatField = FloatField(
        verbose_name="I/O等待CPU使用率(%)",
    )
    cpu_core_count = IntegerField(
        verbose_name="CPU核心数",
    )
    per_core_usage = JSONField(
        verbose_name="每个核心使用率(%)",
        default=list,
    )
    # 内存指标
    memory_total: BigIntegerField = BigIntegerField(
        verbose_name="内存总量(字节)",
    )
    memory_available: BigIntegerField = BigIntegerField(
        verbose_name="可用内存(字节)",
    )
    memory_percent: FloatField = FloatField(
        verbose_name="内存使用率(%)",
    )
    memory_used: BigIntegerField = BigIntegerField(
        verbose_name="已用内存(字节)",
    )
    memory_free: BigIntegerField = BigIntegerField(
        verbose_name="空闲内存(字节)",
    )
    # 磁盘指标(JSON 存储多个磁盘信息)
    disk_metrics = JSONField(
        verbose_name="磁盘指标",
        default=list,
        blank=True,
    )
    # 网络指标
    network_bytes_sent: BigIntegerField = BigIntegerField(
        verbose_name="发送字节数",
    )
    network_bytes_recv: BigIntegerField = BigIntegerField(
        verbose_name="接收字节数",
    )
    network_packets_sent: BigIntegerField = BigIntegerField(
        verbose_name="发送数据包数",
    )
    network_packets_recv: BigIntegerField = BigIntegerField(
        verbose_name="接收数据包数",
    )
    # GPU 指标(JSON 存储多个 GPU 信息)
    gpu_metrics: JSONField = JSONField(
        verbose_name="GPU指标",
        default=list,
        blank=True,
    )

    class Meta:  # type: ignore
        verbose_name = "服务器指标"
        verbose_name_plural = "服务器指标"
        indexes = [
            models.Index(fields=["time"]),
        ]
        # 按时间倒序
        ordering = ["-time"]

    def __str__(self) -> str:
        return f"{self.time}"
